package dev.werillib.android

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import dev.werillib.utils.FileUtil

object ApkUpdateUtil {
    fun getAppVersionName(context: Context): String {
        val packageInfo: PackageInfo = context.packageManager.getPackageInfo(
            context.packageName,
            PackageManager.GET_CONFIGURATIONS
        )
        return packageInfo.versionName
    }

    fun getAppVersionCode(context: Context): Int {
        val packageInfo: PackageInfo = context.packageManager.getPackageInfo(
            context.packageName,
            PackageManager.GET_CONFIGURATIONS
        )
        return packageInfo.versionCode
    }

    fun update(context: Context, url: String) {
        val path = FileUtil.getDownloadApkCachePath(context.packageName)
        AllenVersionChecker
            .getInstance()
            .downloadOnly(
                UIData.create().setDownloadUrl(url)
            )
            .setForceRedownload(true)
            .setDownloadAPKPath(path)
            .executeMission(context)
    }

    fun update(context: Context, url: String, title: String, content: String, isForce: Boolean, block: () -> Unit) {
        val path = FileUtil.getDownloadApkCachePath(context.packageName)
        val uiData = UIData.create()
            .setDownloadUrl(url)
            .setTitle(title)
            .setContent(content)

        AllenVersionChecker
            .getInstance()
            .downloadOnly(uiData)
            .setForceRedownload(true)
            .setDownloadAPKPath(path)
            .apply {
                if (isForce) {
                    this.setForceUpdateListener(block)
                }
            }
            .executeMission(context)
    }

    fun update(context: Context, url: String, silent: Boolean) {
        if (silent) {
            val path = FileUtil.getDownloadApkCachePath(context.packageName)
            AllenVersionChecker
                .getInstance()
                .downloadOnly(
                    UIData.create().setDownloadUrl(url)
                )
                .setDirectDownload(true)
                .setShowDownloadingDialog(false)
                .setShowNotification(false)
                .setShowDownloadFailDialog(false)
                .setForceRedownload(true)
                .setDownloadAPKPath(path)  //安装包保存路径
                .executeMission(context)
        } else {
            update(context, url)
        }
    }

    /**
     * 取消更新
     *
     * @param context
     */
    fun cancel(context: Context) {
        AllenVersionChecker.getInstance().cancelAllMission(context)
    }
}